<?php

class Functions
{
    /**
     * 返回一个有框架生成的page类的分页信息
     * @param stdClass $page
     * @return array
     */
    public static function getPagesByPage(\stdClass $page)
    {
        $return = [
            'items' => $page->items->toArray(),
            'current' => $page->current,
            'before' => $page->before,
            'next' => $page->next,
            'last' => $page->last,
            'total-pages' => $page->total_pages,
            'total-items' => $page->total_items
        ];
        return $return;
    }

    /**
     * 生成一个基于bootstrap的分页html代码段
     * @param array $pages
     * @return string
     */
    public static function genHtmlPages(array $pages)
    {
        $requestUrl = $_SERVER['REQUEST_URI'];
        $host = 'http://' . $_SERVER['HTTP_HOST'];
        //解析查询语句
        $link = $host;
        $queryArray = explode('?', $requestUrl);
        if (!empty($queryArray[0])) {
            $link .= $queryArray[0];
        }
        $link .= '?';
        if (!empty($queryArray[1])) {
            $queryStrings = $queryArray[1];
            //过滤掉分页参数
            $queries = explode('&', $queryStrings);
            foreach ($queries as $key=>$query) {
                $param = explode('=', $query);
                if ($param[0] == 'page') {
                    unset($queries[$key]);
                }
            }
            $queries = implode('&', $queries);
            $link .= $queries;
        }
        $current = $pages['current'];
        $last = $pages['last'];
        $htmlLink = '<nav><ul class="pagination" >';
        //把当前页放在中间
        if ($current-2 > 0) {
            $htmlLink .= '<li class="active"><a href="'. $link . '&page=' . ($current-2) . '">'. ($current-2) .'</a></li> ';
        }
        if ($current-1 >0) {
            $htmlLink .= '<li class="active"><a href="'. $link . '&page=' . ($current-1) . '">'. ($current-1) .'</a></li> ';
        }
        $htmlLink .= '<li class="disabled"><a href="#">'. $current .'</a></li> ';
        if ($current+1 <= $last) {
            $htmlLink .= '<li class="active"><a href="'. $link . '&page=' . ($current+1) . '">'. ($current+1) .'</a></li> ';
        }
        if ($current+2 <= $last) {
            $htmlLink .= '<li class="disabled"><a href="#">'. ($current+2) .'</a></li> ';
        }
        $htmlLink .= '</ul></nav>';
        return $htmlLink;

    }
}